let AreaJson = require('./areadata.js').AreaJson
const ajaxhelp = require("./ajaxhelp.js");
const serviceUrl = getApp().globalData.serviceUrl;



/**
 * 获取所有省份
 */
function getProvinces() {
    var provinces = ['全部'];
	/*ajaxhelp.asyncGet(`${serviceUrl}/areajson.json`).then(resp=>{
		let {statusCode,data,errMsg} =resp;
		if(errMsg === "request:ok"){
			debugger;
			AreaJson = data;
		}

	}).finally(()=>{
		//debugger;
		for (var i = 0; i < AreaJson.length; i++) {
			provinces.push(AreaJson[i].name);
		}
	});*/
	for (var i = 0; i < AreaJson.length; i++) {
		provinces.push(AreaJson[i].name);
	}
	return provinces;
}


/**
 * 获取省对应的所有城市
 */
function getCitys(provinceIndex) {
  var citys = ['全部'];
  if (provinceIndex>=0){
    for (var i = 0; i < AreaJson[provinceIndex].city.length; i++) {
      citys.push(AreaJson[provinceIndex].city[i].name);
    }
  }
	return citys;
}

/**
 * 获取省市对应的所有地区
 */
function getAreas(provinceIndex, cityIndex) {
  var areas = ['全部'];
  if (provinceIndex >= 0 && cityIndex>=0){
    areas=areas.concat(AreaJson[provinceIndex].city[cityIndex].area);
  }
	return areas;
}


/**
 * 获取所有省份下标
 */
function getProvinceNameIndex(provinceName) {
	return AreaJson.findIndex(function(item, index, array) {
		return item.name === provinceName
	});
}


/**
 * 获取省对应的所有城市下标
 */
function getCityNameIndex(provinceName, ctiyName) {
	let provinceIndex = this.getProvinceNameIndex(provinceName);
	console.log(AreaJson[provinceIndex]);
	if (AreaJson[provinceIndex].city) {
		return AreaJson[provinceIndex].city.findIndex(function(item, index, array) {
			return item.name === ctiyName
		})
	}
}

/**
 * 获取省市对应的所有地区下标
 */
function getAreaNameIndex(provinceName, ctiyName, areaName) {
	console.log(provinceName, ctiyName, areaName)
	let provinceIndex = this.getProvinceNameIndex(provinceName);
	let cityIndex = this.getCityNameIndex(provinceName, ctiyName);
	//debugger;
	if (cityIndex != -1 && AreaJson[provinceIndex].city[cityIndex]) {
		return AreaJson[provinceIndex].city[cityIndex].area
		.findIndex(function(item, index, array) {
			return item === areaName
		});
	}
}

module.exports = {
	getProvinces: getProvinces,
	getCitys: getCitys,
	getAreas: getAreas,
	getProvinceNameIndex: getProvinceNameIndex,
	getCityNameIndex: getCityNameIndex,
	getAreaNameIndex: getAreaNameIndex
}
